<template>
    <div class="" v-if="showCalendar" @click.stop="cancel">
        <div class="calendar">
            <div class="content" @tap.stop>
                <div class="title">
                    <div class="switch">
                        <div class="left" :class="{ active: type === 'solar' }" @click="switchBtn('solar')">
                            公历
                        </div>
                        <div class="right" :class="{ active: type === 'lunar' }" @click="switchBtn('lunar')">
                            农历
                        </div>
                        <div class="bg" :class="type"></div>
                    </div>
                    <!-- <div class="ignore-year">忽略年份</div> -->
                </div>
                <div style="height: 300px">

                    <el-select class="year-select" v-model="selectedYear" placeholder="选择年份" @change="handleYearChange">
                        <el-option v-for="year in years" :key="year" :label="year + '年'" :value="year"></el-option>
                    </el-select>

                    <el-select class="year-select" v-model="selectedMonth" placeholder="选择月份"
                        @change="handleMonthChange">
                        <el-option v-for="(month, index) in months" :key="index" :label="month"
                            :value="month"></el-option>
                    </el-select>
                    <el-select class="year-select" v-model="selectedDay" placeholder="选择日期" @change="handleDayChange">
                        <el-option v-for="(item, index) in days" :key="index" :label="item" :value="item"></el-option>
                    </el-select>
                    <el-select class="year-select" v-if="isHourShow" v-model="selectedHour" placeholder="选择小时"
                        @change="handleHourChange">
                        <el-option v-for="hour in lunarHour" :key="isActive ? hour.solar : hour.label"
                            :label="isActive ? hour.solar : hour.label"
                            :value="isActive ? hour.solar : hour.label"></el-option>
                    </el-select>
                    <el-select class="year-select" v-model="selectedMinute" placeholder="选择分钟"
                        @change="handleMinuteChange">
                        <el-option v-for="minute in lunarMinute" :key="minute" :label="minute"
                            :value="minute"></el-option>
                    </el-select>
                </div>
                <div class="" v-if="isSwitch">
                    <span slot="footer" class="dialog-footer">
                        <!-- <el-button @click="cancel">取 消</el-button> -->
                        <el-button type="primary" @click="sure">确 定</el-button>
                    </span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import conversion from "./calendar.js";
import lunarHour from "./information.js";
export default {
    name: "e-run-calendar",
    data() {
        return {
            selectedYear: 2025,
            selectedMonth: "",
            selectedDay: "",
            selectedHour: "",
            selectedMinute: "",

            oldYear: 1900, // 最大年份
            type: "solar", // lunar农历，solar公历
            isActive: true, // true公历
            showData: "", // 显示数据
            checked: true,
            years: [],
            months: [],
            days: [],

            lunarHour: [],
            lunarMinute: ["未知"],
            date: "",
            hour: "",
            minute: "",
            leap_month: 0, // 1为闰月0为非闰月
            sureYear: "2024", // 默认弹出显示年份
            sureMonth: "1", // 默认弹出显示月份

            showYear: "",
            showMonth: "",
            nextFinally: true,
            selectOptionsIndex: [],
            selectedIndexYear: 0,
            selectedIndexMonth: 0,
            selectedIndexDay: 0,
            selectedIndexHour: 0,
            selectedIndexMinute: 0,
        };
    },
    props: {
        selectValue: {
            type: Array,
            default: () => [124, 9, 10, 10, 10],
        },
        showCalendar: {
            type: Boolean,
            default: () => false,
        },
        isHourShow: {
            type: Boolean,
            default: false,
        },
        isSwitch: {
            type: Boolean,
            default: true,
        },
        selectOptions: {
            type: Array,
            default: () => [30, 0, 0, 0],
        },
    },
    watch: {
        showCalendar(newVal, oldVal) {
            if (newVal) this.getTime();
        },
        selectOptions(newVal, oldVal) {
            this.selectValue = newVal;
        },
    },
    created() {
        this.getTime();

        // 使用Vue事件总线替代uni事件监听（需先在main.js创建事件总线）
        this.$bus.$on("selectOptionsArr", this.handleSelectOptions);

        // 时间选项初始化
        for (let i = 0; i < 60; i++) {
            // 建议使用let代替var
            this.lunarMinute.push(`${i}分`); // 使用模板字符串
        }
    },
    beforeDestroy() {
        // 改用组件销毁生命周期
        this.$bus.$off("selectOptionsArr", this.handleSelectOptions);
    },
    mounted() { },
    methods: {
        handleYearChange(value) {
            console.log(value, "value");
            this.selectValue[0] = this.years.findIndex(option => option == value);
            this.bindChange()
        },
        handleMonthChange(value) {
            console.log(value, "value");
            this.selectValue[1] = this.months.findIndex(option => option == value);
            this.bindChange()
            // 根据年份和月份生成日期数组
        },
        handleDayChange(value) {
            console.log(value, "value");
            this.selectValue[2] = this.days.findIndex(option => option == value);
            this.bindChange()
        },
        handleHourChange(value) {
            console.log(value, "value");
            this.selectValue[3] = this.lunarHour.findIndex(option => option.solar == value);
            this.bindChange()
        },
        handleMinuteChange(value) {
            this.selectValue[4] = this.lunarMinute.findIndex(option => option == value);
            this.bindChange()
        },
        generateDaysForYearAndMonth(year, month) {
            // 根据年份和月份生成日期数组的逻辑
            // 注意：这里需要您自己实现日期生成的逻辑
            return [
                /* ... 日期数组 ... */
            ];
        },
        cancel() {
            this.$emit("cancel");
        },
        // 提交
        sure() {
            if (!this.nextFinally) {
                console.log("别着急，正在选时间");
                return false;
            }
            if (this.selectedYear == "") {
                this.$message("请选择年份")
                return false;
            }
            if (this.selectedMonth == "") {
                this.$message("请选择月份")
                return false;
            }
            if (this.selectedDay == "") {
                this.$message("请选择日期")
                return false;
            }
            if (this.selectedHour == "") {
                this.$message("请选择事件")
                return false;
            }
            let data = {
                text: this.showData, // 显示数据
                type: this.type,
                brithday: {
                    "brithday[date]": this.date,
                    "brithday[hour]": this.hour,
                    "brithday[minute]": this.minute,
                    "brithday[type]": this.type,
                    // "brithday[leap_month]":this.leap_month,
                },
                newBirthday: {
                    brithday: {
                        date: this.date,
                        hour: this.hour,
                        minute: this.minute,
                        type: this.type,
                    },
                },
                date: this.date,
                hour: this.hour || 0,
                minute: this.minute || 0,
                year: this.showYear,
                month: this.coverTo(Number(this.showMonth)),
                day: this.coverTo(this.selectValue[2] + 1),
            };
            if (this.type == "lunar") {
                data.brithday["brithday[leap_month]"] = this.leap_month;
                data.newBirthday.brithday.leap_month = this.leap_month;
                data.leap_month = this.leap_month;
            }
            this.$emit("confirm", data);
            this.nextFinally = true;
        },
        // 进来获取公历的1990-02-10 10,初始化
        getTime() {
            const date = new Date();
            const year = date.getFullYear();
            const month = date.getMonth() + 1;
            const day = date.getDate();
            this.years = [];
            this.days = [];
            this.months = [];
            for (let i = this.oldYear; i <= 2099; i++) {
                if (this.isActive) {
                    this.years.push(i);
                } else {
                    // this.years.push(conversion.toChinaYear(i));
                    this.years.push(i);
                }
            }
            console.log(
                this.sureYear,
                this.sureMonth,
                this.selectValue,
                "this.sureYear, this.sureMonth, this.selectValue"
            );
            if (this.isActive) {
                this.getsolarMonthDays(this.sureYear, this.sureMonth, this.selectValue);
            } else {
                this.getlunarMonthDays(this.sureYear, this.sureMonth, this.selectValue);
            }
            this.lunarHour = lunarHour.lunarHour;
        },
        bindChange: function (e) {
            const val = this.selectValue;
            let year = val[0] + this.oldYear,
                month = val[1] + 1,
                day = val[2] + 1;
            this.days = [];
            this.months = [];

            // this.nextFinally = false;
            // 公历返回每个月天数
            if (this.isActive) {
                this.getsolarMonthDays(year, month, val);
            } else {
                this.getlunarMonthDays(year, month, val);
            }
        },
        // D=>DD,M=>MM,日，月转换 1=>01
        coverTo(num) {
            return num < 10 ? "0" + num : num;
        },
        // 获取公历的月份和天数
        getsolarMonthDays(year, month, val) {
            for (let i = 1; i <= 12; i++) {
                this.months.push(i + "月");
            }
            for (let i = 1; i <= conversion.solarDays(year, month); i++) {
                this.days.push(i + "日");
            }
            this.leap_month = 0;
            this.date = `${val[0] + this.oldYear}-${this.coverTo(
                val[1] + 1
            )}-${this.coverTo(val[2] + 1)}`;
            this.hour = val[3];
            console.log(this.hour);
            this.minute = val[4] - 1;
            let showHour = "";
            console.log(val[3] < 10);
            if (val[3] < 10) {
                showHour = " 0" + `${val[3] + "时"}`;
            } else {
                showHour = ` ${val[3] + "时"}`;
            }
            let showMinute = "";
            if (showHour !== "") {
                console.log(val);
                console.log(val[4]);
                showMinute = this.isHourShow
                    ? `${val[4] != 0 ? val[4] - 1 + "分" : ""}`
                    : "";
            }
            console.log(showMinute);
            this.showData = `公历${val[0] + this.oldYear}年${this.coverTo(
                val[1] + 1
            )}月${this.coverTo(val[2] + 1)}日${showHour}${showMinute}`;

            this.showYear = `${val[0] + this.oldYear}`;
            this.showMonth = `${val[1] + 1}`;
            setTimeout((e) => {
                this.nextFinally = true;
            }, 200);
        },
        // 获取农历的月份和天数
        getlunarMonthDays(year, month, e) {
            let leap_month = conversion.leapMonth(year);
            // 返回农历 闰月没有就返回0
            for (let i = 1; i <= 12; i++) {
                this.months.push(conversion.toChinaMonth(i));
                if (i == leap_month) {
                    this.months.push("闰" + conversion.toChinaMonth(i));
                }
            }
            // 农历返回天数
            // **leapMonth 返回闰月 conversion.leapMonth(year)
            // **monthDays 返回非闰月的天数
            // **leapDays 返回闰月的天数
            if (
                conversion.leapMonth(year) != 0 &&
                (conversion.leapMonth(year) == month ||
                    month - 1 == conversion.leapMonth(year))
            ) {
                for (
                    let i = 1;
                    i <= conversion.leapDays(year, conversion.leapMonth(year));
                    i++
                ) {
                    this.days.push(conversion.toChinaDay(i));
                }
            } else {
                let lunarMonth = "";
                if (conversion.leapMonth(year)) {
                    lunarMonth = month < conversion.leapMonth(year) ? month : month - 1;
                } else {
                    lunarMonth = month;
                }
                for (let i = 1; i <= conversion.monthDays(year, lunarMonth); i++) {
                    this.days.push(conversion.toChinaDay(i));
                }
            }
            if (e) {
                const val = e;
                let year = val[0] + this.oldYear,
                    month = val[1],
                    day = val[2],
                    hour = val[3] ? val[3] : 0,
                    minute = val[4] ? val[4] : 0,
                    m = "",
                    d = "",
                    mi = "",
                    h = "";
                m = this.months[month];
                d = this.days[day];
                h = this.lunarHour[hour].value + "时";
                mi = this.lunarMinute[minute];
                this.leap_month = month == leap_month && leap_month != 0 ? 1 : 0;
                let lunarToMonth = this.coverTo(
                    leap_month != 0
                        ? month + 1 <= leap_month
                            ? month + 1
                            : month
                        : month + 1
                );
                this.date = `${year}-${lunarToMonth}-${this.coverTo(day + 1)}`;
                this.hour = hour;
                let showHour = this.isHourShow ? ` ${h}` : "";
                let showMinute = "";
                if (showHour === " 24时") {
                    mi = "";
                }
                if (mi === "未知") {
                    mi = "";
                }
                this.showData = `农历${year}年${m}${d}${showHour == " 24时" ? "" : showHour
                    }${mi}`;
                this.showYear = year;
                this.showMonth = lunarToMonth;
            }
            setTimeout((e) => {
                this.nextFinally = true;
            }, 150);
        },
        // 切换公历<=>农历 回显以及切换 this.$refs.yourname.switchBtb(type,data),type:"lunar" or "solar", data:{date:"1992-02-10",hour:3,leap_month:"0",type:"lunar"}
        switchBtn(type, data) {
            console.log("切换了", this.selectValue);
            this.selectedYear = "";
            this.selectedMonth = "";
            this.selectedDay = "";
            this.selectedHour = "";
            this.selectedMinute = "";
            // 农历公历互相联动切换
            if (this.type == type) {
                return false;
            }
            if (type == "lunar") {
                // 公历切换为农历
                let solarYear = this.selectValue[0] + this.oldYear; // 公历年份
                let leapMonth = conversion.leapMonth(solarYear);
                let solarMonth = this.selectValue[1] + 1, // 公历年月份
                    solarDay = this.selectValue[2] + 1, // 公历年日份
                    hour = this.selectValue[3],
                    minute = this.selectValue[4];
                let lunarDate = conversion.solar2lunar(solarYear, solarMonth, solarDay);
                this.sureYear = lunarDate.lYear; // 默认弹出显示年份
                this.sureMonth = lunarDate.lMonth; // 默认弹出显示月份
                this.leap_month = leapMonth != 0 ? 1 : 0;
                let y = lunarDate.lYear - this.oldYear,
                    m =
                        this.leap_month == 0
                            ? lunarDate.lMonth - 1
                            : this.selectValue[1] < leapMonth
                                ? lunarDate.lMonth - 1
                                : lunarDate.lMonth,
                    d = lunarDate.lDay - 1;
                this.selectValue = [y, m, d, hour, minute]; // 默认弹出选择的状态1990-06-10 10 10
            } else {
                // 农历切换为公历
                let lunarYear = this.selectValue[0] + this.oldYear; // 农历年份
                let leapMonth = conversion.leapMonth(lunarYear); // 一年中的几月份是闰月
                let lunarMonth =
                    leapMonth == 0
                        ? this.selectValue[1] + 1
                        : this.selectValue[1] + 1 <= leapMonth
                            ? this.selectValue[1] + 1
                            : this.selectValue[1], // 农历年月份
                    lunarDay = this.selectValue[2] + 1, // 农历年日份
                    hour = this.selectValue[3],
                    minute = this.selectValue[4];
                console.log(lunarYear, lunarMonth, lunarDay, "11111111");
                let lunarDate = conversion.lunar2solar(
                    lunarYear,
                    lunarMonth,
                    lunarDay,
                    leapMonth == this.selectValue[1] ? true : false
                );
                console.log(lunarDate, "lunarDatelunarDate");
                this.sureYear = lunarDate.cYear; // 默认弹出显示年份
                this.sureMonth = lunarDate.cMonth; // 默认弹出显示月份
                this.leap_month = leapMonth != 0 ? 1 : 0;
                let y = lunarDate.cYear - this.oldYear,
                    m = lunarDate.cMonth - 1,
                    d = lunarDate.cDay - 1;
                this.selectValue = [y, m, d, hour, minute]; // 默认弹出选择的状态1990-06-10 10 10
                console.log(this.sureYear, this.sureMonth, this.selectValue, "00000");
            }
            this.isActive = type == "solar" ? true : false;
            this.type = type;
            this.getTime();
        },
    },
};
</script>

<style lang="scss" scoped>
.u-mask-zoom {
    transform: scale(1, 1);
}

.calendar {
    display: flex;
    align-items: flex-end;
    justify-content: center;
    height: 100%;

    .content {
        position: relative;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 100%;
        // height: 100%;
        background-color: #fff;
        border-top-left-radius: 12px; // 12rpx / 2 assuming 375px screen width (but this is arbitrary)
        border-top-right-radius: 12px; // 12rpx / 2
        animation: switchOpen 500ms linear;

        @keyframes switchOpen {
            from {
                top: 100%;
            }

            to {
                top: 0%;
            }
        }

        .title {
            display: flex;
            flex-direction: row;
            align-items: center;
            width: 100%;

            position: relative;

            background-color: #ffffff;
            border-top-left-radius: 12px; // 12rpx / 2
            border-top-right-radius: 12px; // 12rpx / 2

            .switch {
                width: 100px; // 200rpx / 2
                height: 40px; // 80rpx / 2
                line-height: 40px; // 80rpx / 2
                color: #a6a6a6;
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);

                .left,
                .right {
                    font-size: 14px; // 28rpx / 2 (but note that font sizes may need to be rounded to valid CSS values)
                    display: inline-block;
                    width: 50px; // 100rpx / 2 (but this doesn't make sense for width, consider adjusting)
                    text-align: center;
                }

                .bg {
                    background-color: #1860ff;
                    border-radius: 15px; // 30px / 2 (rounded)
                    height: 1.5px; // 3px / 2 (but note that half-pixel values may not render correctly)
                    width: 20px; // 40rpx / 2
                    position: absolute;
                    bottom: 0px;
                    z-index: 0;
                }

                .active {
                    color: #1860ff;
                }

                .lunar {
                    left: 65px;
                    animation: switchsolar 500ms;
                }

                @keyframes switchsolar {
                    0% {
                        left: 12px;
                    }

                    100% {
                        left: 65px;
                    }
                }

                .solar {
                    left: 12.5px;
                    animation: switchlunar 500ms;
                }

                @keyframes switchlunar {
                    0% {
                        left: 70px;
                    }

                    100% {
                        left: 12px;
                    }
                }

                // ... (other styles omitted for brevity)
            }

            // ... (other styles omitted for brevity)
        }

        .year-select {
            margin: 10px;
        }

        .bottom {
            height: 50px; // 100rpx / 2
            width: 100%;
            display: flex;
            background-color: #f7f7f7;

            div {
                width: 50%;
                line-height: 55px; // 110rpx / 2 (but rounded to a more sensible line height)
                text-align: center;
                font-size: 14px; // 28rpx / 2 (but note that font sizes may need to be rounded)
            }

            // ... (other styles omitted for brevity)
        }
    }
}
</style>
